package com.bb.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bb.dto.UserDto;
import com.bb.pojo.Role;
import com.bb.pojo.User;
import com.bb.service.IUserService;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private IUserService userService;
	
	/**
	 * 查询所有的用户信息
	 * @param m
	 * @return
	 */
	@RequestMapping("/query")
	public String query(Model m){
		m.addAttribute("list", userService.query(null));
		return "user/user";
	}
	
	/**
	 * 分页查询用户信息
	 * @param m
	 * @return
	 */
	@RequestMapping("/queryPage")
	public String queryPage(Model m,UserDto dto){
		PageInfo<User> pageInfo = userService.queryUserByPage(dto);
		m.addAttribute("pageModel", pageInfo);
		return "user/user";
	}
	
	/**
	 * 进入添加或者修改的方法之前跳转的方法
	 * @return
	 */
	@RequestMapping("/goAddOrUpdate")
	public String goAddOrUpdate(Integer userId,Model m){
		// 查询所有的角色信息
		List<Role> roles = userService.queryRole();
		m.addAttribute("roles", roles);
		if(userId !=null){
			UserDto dto = userService.getUpdateInfo(userId);
			m.addAttribute("dto", dto);
		}
		return "user/user_update";
	}
	@RequestMapping("/saveOrUpdate")
	public String saveOrUpdate(UserDto dto){
		if(dto !=null && dto.getUser()!=null && dto.getUser().getUserId()!=null ){
			// 表示更新数据
			userService.updateUserAndRole(dto);
		}else{
			Integer count = userService.saveUserAndRole(dto);
		}
		
		return "redirect:/user/queryPage";
	}
	
	@RequestMapping("/delete")
	public String deleteUser(Integer userId){
		userService.deleteUser(userId);
		return "redirect:/user/queryPage";
	}
	
	public static void main(String[] args) throws IOException {
		InputStream in = Resources.getResourceAsStream("");
		// 获取SqlSessionFactory对象同时加载配置文件到Configuration对象中
		SqlSessionFactory  factory = new SqlSessionFactoryBuilder().build(in);
		SqlSession session = factory.openSession();
		session.selectList("");
	}
	
}
